/*
 * ProcessEditorUI.java
 *
 * Created on October 26, 2008, 7:33 PM
 */

package deadlocksim.gui;

import java.io.IOException;
import java.util.*;
import deadlocksim.*;
import deadlocksim.backend.*;
import deadlocksim.backend.process.*;
import deadlocksim.backend.resources.*;
import deadlocksim.backend.resources.ResourceManager.*;
import deadlocksim.backend.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author  KarenPell
 */
public class ProcessEditorUI extends javax.swing.JFrame //implements ActionListener 
{
    
    private final static String newline = "\n";
    private String filename = null;
    private MainPage mainPage;
    private DeadlockSim mySim;
    //private ResourceManager resourceList;
    
    /** Creates new form ProcessEditorUI */
    public ProcessEditorUI(MainPage mainP) {
        initComponents();
        mainPage = mainP;
        this.mySim = mainPage.getDeadlockSim();
        //this.mySim.refreshDisplay();
        //this.mySim.getResourceDisplay();
        //this.mySim.getResourceManager();
        //OpenButton.addActionListener(this);
        //SaveButton.addActionListener(this);
        if (this.ReleaseResourceList.getItemCount() == 0) {
            this.ReleaseResourceButton.setEnabled(false);
        }
        buildResourceList(this.mySim);
    }
   
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        ComputeTime = new javax.swing.JTextField();
        ComputeLabel = new javax.swing.JLabel();
        addResourceList = new javax.swing.JComboBox();
        RequestLabel = new javax.swing.JLabel();
        ReleaseResourceList = new javax.swing.JComboBox();
        ReleaseLabel = new javax.swing.JLabel();
        HaltLabel = new javax.swing.JLabel();
        ComputeButton = new javax.swing.JButton();
        RequestResourceButton = new javax.swing.JButton();
        ReleaseResourceButton = new javax.swing.JButton();
        HaltButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        processListing = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jButtonRemove = new javax.swing.JButton();
        OpenButton = new javax.swing.JButton();
        SaveButton = new javax.swing.JButton();
        jButtonLoad = new javax.swing.JButton();
        DoneButton = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Process Editor"));

        ComputeLabel.setText("Compute");

        addResourceList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addResourceListActionPerformed(evt);
            }
        });

        RequestLabel.setText("Request Resource");

        ReleaseResourceList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ReleaseResourceListActionPerformed(evt);
            }
        });

        ReleaseLabel.setText("Release Resource");

        HaltLabel.setText("Halt");

        ComputeButton.setText("Add Compute");
        ComputeButton.setToolTipText("Enter the number of clock ticks to compute and then select Add.");
        ComputeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ComputeButtonActionPerformed(evt);
            }
        });

        RequestResourceButton.setText("Add Request");
        RequestResourceButton.setToolTipText("Select the resource that you would like to request and then select Add.");
        RequestResourceButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RequestResourceButtonActionPerformed(evt);
            }
        });

        ReleaseResourceButton.setText("Add Release");
        ReleaseResourceButton.setToolTipText("Select the resource that you would like to release and then select Add.");
        ReleaseResourceButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ReleaseResourceButtonActionPerformed(evt);
            }
        });

        HaltButton.setText("Add Halt");
        HaltButton.setToolTipText("Halt should be the last command in the process. Select Add when the process is complete.");
        HaltButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                HaltButtonActionPerformed(evt);
            }
        });

        processListing.setColumns(20);
        processListing.setRows(5);
        jScrollPane1.setViewportView(processListing);

        jButtonRemove.setText("Remove Selected Entry");
        jButtonRemove.setToolTipText("Select text in the listing and then remove.");
        jButtonRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(ComputeLabel)
                                    .addComponent(RequestLabel)
                                    .addComponent(ReleaseLabel))
                                .addGap(33, 33, 33)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(ReleaseResourceList, 0, 106, Short.MAX_VALUE)
                                    .addComponent(ComputeTime, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                                    .addComponent(addResourceList, javax.swing.GroupLayout.Alignment.TRAILING, 0, 106, Short.MAX_VALUE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(HaltLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(26, 26, 26)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(RequestResourceButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(ComputeButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(ReleaseResourceButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(HaltButton, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(386, 386, 386)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButtonRemove, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {ComputeButton, HaltButton, ReleaseResourceButton, RequestResourceButton});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                            .addComponent(ComputeLabel)
                            .addComponent(ComputeButton)
                            .addComponent(ComputeTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(9, 9, 9)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                            .addComponent(RequestLabel)
                            .addComponent(addResourceList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(RequestResourceButton))
                        .addGap(12, 12, 12)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                            .addComponent(ReleaseLabel)
                            .addComponent(ReleaseResourceList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(ReleaseResourceButton))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(HaltButton, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(HaltLabel)))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {ComputeButton, HaltButton, ReleaseResourceButton, RequestResourceButton, jButtonRemove});

        OpenButton.setText("Open Process File");
        OpenButton.setToolTipText("Open is used to open an existing process for editing.");
        OpenButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenButtonActionPerformed(evt);
            }
        });

        SaveButton.setText("Save To File");
        SaveButton.setToolTipText("Save the changes made to the process.");
        SaveButton.setEnabled(false);
        SaveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveButtonActionPerformed(evt);
            }
        });

        jButtonLoad.setText("Load Process into Sim");
        jButtonLoad.setToolTipText("Select Load to add the file to the simulator.");
        jButtonLoad.setEnabled(false);
        jButtonLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLoadActionPerformed(evt);
            }
        });

        DoneButton.setText("Exit Editor");
        DoneButton.setToolTipText("Closes the process editor form.");
        DoneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DoneButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(OpenButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(SaveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonLoad)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(DoneButton, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(17, 17, 17))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OpenButton)
                    .addComponent(SaveButton)
                    .addComponent(jButtonLoad)
                    .addComponent(DoneButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void ComputeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ComputeButtonActionPerformed
// add compute time to the process
    // jason 
    String numberFieldText = this.ComputeTime.getText();
    Integer numberFieldInt; 
    try
    {
        numberFieldInt = new Integer(numberFieldText);
        if(numberFieldInt <= 0)
            throw new Exception();
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(this, "You must specify positive whole numbers only in the Compute field!");
        return;
    }
    String text = "C " + this.ComputeTime.getText();
    this.processListing.append(text + newline);
    
}//GEN-LAST:event_ComputeButtonActionPerformed

private void DoneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DoneButtonActionPerformed
    this.setVisible(false);
}//GEN-LAST:event_DoneButtonActionPerformed

private void OpenButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenButtonActionPerformed
    // Open the selected file
    //OpenButton.addActionListener(this);
    //OpenButton.addActionListener(new ProcessSaveUI());
    this.processListing.setText("");
    File theFile = openFile();
    filename = theFile.getAbsolutePath();
    jButtonLoad.setEnabled(true);
}//GEN-LAST:event_OpenButtonActionPerformed

private void HaltButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HaltButtonActionPerformed
// add halt to the process and disable the other buttons since halt is the last action in the process
    this.processListing.append("H"); 
    this.ComputeButton.setEnabled(false);
    this.RequestResourceButton.setEnabled(false);
    this.ReleaseResourceButton.setEnabled(false);
    this.HaltButton.setEnabled(false);
    this.SaveButton.setEnabled(true);
    this.jButtonLoad.setEnabled(true);
}//GEN-LAST:event_HaltButtonActionPerformed

private void RequestResourceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RequestResourceButtonActionPerformed
// Add selected resource to the process. Add it to the list of items that can be released
    String text = "R " + this.addResourceList.getSelectedItem();
    this.processListing.append(text + newline);
    this.ReleaseResourceList.addItem(this.addResourceList.getSelectedItem());
    this.ReleaseResourceButton.setEnabled(true);
    // decided not to remove the item from the list once it has been added to the process
    //this.AddResourceList.removeItem(this.AddResourceList.getSelectedItem());
    //if (this.AddResourceList.getItemCount() == 0) {
    //    this.RequestResourceButton.setEnabled(false);
    //}
}//GEN-LAST:event_RequestResourceButtonActionPerformed

private void ReleaseResourceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReleaseResourceButtonActionPerformed
// Add release selected resource to the process. Remove the item from the list.
// Add the item back to the items that can be added.
    String text = "F " + this.ReleaseResourceList.getSelectedItem();
    this.processListing.append(text + newline);
    // no longer removing the item from the list so there is no need to add it back.
    //this.AddResourceList.addItem(this.ReleaseResourceList.getSelectedItem());
    this.ReleaseResourceList.removeItem(this.ReleaseResourceList.getSelectedItem());
    if (this.ReleaseResourceList.getItemCount() == 0){
        this.ReleaseResourceButton.setEnabled(false);
    }
}//GEN-LAST:event_ReleaseResourceButtonActionPerformed

private void SaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveButtonActionPerformed
    if(processListing.getText() == null || processListing.getText().equals(""))
        return;
    File theFile = saveAs(null);
    filename = theFile.getAbsolutePath();
    jButtonLoad.setEnabled(true);
        
    /*
        try {
            Queue<ProcessAction> process1Actions = p1Loader.BuildActionQueue();//GEN-LAST:event_SaveButtonActionPerformed
            DeadlockProcess process1 = mySim.createProcess(process1Actions);
        } catch (IOException ex) {
            Logger.getLogger(ProcessEditorUI.class.getName()).log(Level.SEVERE, null, ex);
        }*/
}                                          

    public File saveAs(String optionalFileName) {
        // jason. karen changed to return a file
        File theFile = null;
        JFileChooser fc = null;
        int option = 0;
        
        
        
        if(optionalFileName == null || optionalFileName.equals(""))
        {
            fc = new JFileChooser(".");
            option = fc.showSaveDialog(this);
            theFile = fc.getSelectedFile();
        }
        else
        {
            theFile = new File(optionalFileName);
        
            try
            {
                if(theFile.exists())
                {
                    theFile.delete();
                    theFile.createNewFile();
                }
                else
                    theFile.createNewFile();
            }
            catch(Exception e)
            {
                mySim.sendMessage("Could not write processes file: " + e.getMessage(), true);
            }
            
            if(! theFile.exists())
            {
                fc = new JFileChooser(".");
                option = fc.showSaveDialog(this);
                theFile = fc.getSelectedFile();
            }
        }
        
        // jason. karen changed to return a file
        
        
        if (( fc != null && JFileChooser.APPROVE_OPTION == option)
                || (fc == null && theFile.exists()))
        {
          
            try 
            {
                BufferedWriter out = new BufferedWriter(new FileWriter(theFile));
                String contents = processListing.getText();
                String[] lines = contents.split(newline);
                for(int i = 0; i < lines.length; i++)
                {
                    out.write(lines[i]);
                    out.newLine();
                }
                out.close();
                System.out.println(contents);
            } 
            catch (IOException e) 
            {
                System.err.println("Can't write file: " + e.getMessage() + "\n" + e.getStackTrace());
                return null;
            }
            return theFile;

        }
        return null;
       
    }

    public File openFile() 
    {
        // open the selected file and put the contents in the process listing
        JFileChooser fc = new JFileChooser(".");
        int option = fc.showOpenDialog(this);
        File theFile = fc.getSelectedFile();
        int i=0;
        //FileNameExtensionFilter filter = new FileNameExtensionFilter(
        //"Text Documents", "txt");
        //fc.setFileFilter(filter);
        try
        {
            BufferedReader in = new BufferedReader(new FileReader(theFile));
            // used sample from http://www.wellho.net/mouth/1239_End-of-File-on-a-Java-BufferedReader.html
            while (true){
                if (! in.ready()) break;
                    String next_line = in.readLine();
                    this.processListing.append(next_line + newline);
                    i++;
            }
        }
        catch (IOException e)
        {
                System.err.println("Can't read file: " + e.getMessage() + "\n" + e.getStackTrace());
                return null;            
        }
        return theFile;
    }
    
private void addResourceListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addResourceListActionPerformed
// TODO add your handling code here:  
}//GEN-LAST:event_addResourceListActionPerformed

private void ReleaseResourceListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReleaseResourceListActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_ReleaseResourceListActionPerformed

private void jButtonRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveActionPerformed
// Remove the selected entry from the text listing. Allows editing of the file.
    String editText = this.processListing.getSelectedText();
    if(editText == null)
        return;
    String[] lines = editText.split(newline);
    for(int i = 0; i < lines.length; i++)
    {
        String firstLetter = lines[i].substring(0, 1);//editText.substring(0,1);
        String resourceText = "";
        if (lines[i].length() > 1) {
            resourceText = lines[i].substring (2);
        }
        String request = "R";
        String freeResource = "F";
        String HaltProgram = "H";
        this.processListing.replaceSelection("");
        String leftOverText = processListing.getText().trim();
         String[] lines2 = leftOverText.split(newline);
        leftOverText = "";
        for(int w = 0; w < lines2.length; w++)
        {
            if(! (lines2[w].trim()).equals("")) {
                leftOverText = leftOverText + lines2[w]+newline;
            }
        }
        processListing.setText(leftOverText);
        // Removed the request for the resource. Remove the resource from the list to release.
        // Add the resource to the list of resources. Enable the request resource.
        if (firstLetter.equals(request)) {
            //this.AddResourceList.addItem(resourceText);
            this.RequestResourceButton.setEnabled(true);
            this.ReleaseResourceList.removeItem(resourceText);
            if (this.ReleaseResourceList.getItemCount() == 0) {
                this.ReleaseResourceButton.setEnabled(false);
            }
        }
        // Removed the freeing of the resource. Add the resource back to the list to be freed.
        // Enable the button (would have been disabled if the list was empty).
        else if (firstLetter.equals(freeResource)) {
            this.ReleaseResourceList.addItem(resourceText);
            this.ReleaseResourceButton.setEnabled(true);
        }
        // Removed the halt of the process. Enable all buttons.
        else if (firstLetter.equals(HaltProgram)) {
            this.RequestResourceButton.setEnabled(true);
            this.ReleaseResourceButton.setEnabled(true);
            this.HaltButton.setEnabled(true);
            this.ComputeButton.setEnabled(true);
            this.jButtonLoad.setEnabled(true);
            this.SaveButton.setEnabled(true);
        }
    }
}//GEN-LAST:event_jButtonRemoveActionPerformed

private void jButtonLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLoadActionPerformed
// TODO add your handling code here:
    //JOptionPane.showMessageDialog(this, theFile);
    //DeadlockSim mySim = new DeadlockSim();
    if(processListing.getText() == null || processListing.getText().equals(""))
        return;
    if(filename == null)
    {
        filename = "processes.temp.txt";
        saveAs(filename);
    }
    
    ProcessFileLoader processLoader = new ProcessFileLoader(filename);
    try 
    {
        Queue<ProcessAction> pActions = processLoader.BuildActionQueue();
        if(pActions == null || pActions.size() == 0)
        {
            this.mySim.sendMessage("Could not process actions in the file.", true);
        }
        this.mySim.createProcess(pActions);
        
        processListing.setText("");
        this.RequestResourceButton.setEnabled(true);
        this.ComputeButton.setEnabled(true);
        this.HaltButton.setEnabled(true);
        this.jButtonLoad.setEnabled(false);
        this.SaveButton.setEnabled(false);
        
        filename = null;
        mySim.refreshDisplay();
        //DeadlockResourceDisplay display = this.mySim.getResourceDisplay();
        //display.rebuildDisplay();
        //mySim.refreshDisplay();
        //mySim.getResourceDisplay();
    } catch (IOException ex) 
    {
        System.err.println("Exception in process load button.");
        Logger.getLogger(ProcessEditorUI.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(this, "exception in load button.");
    }    
}//GEN-LAST:event_jButtonLoadActionPerformed
    public Integer buildResourceList(DeadlockSim sim)
    // Karen, Rafal, Jason
    {
        LinkedList<Integer> resourceTypes = sim.getResourceManager().getResourceTypes();
        Iterator<Integer> iter = resourceTypes.iterator();
        addResourceList.removeAllItems();
        while(iter.hasNext())
        {
            this.addResourceList.addItem(iter.next().toString());
            //JOptionPane.showMessageDialog(this, iter.next().toString());
        }    
        return this.addResourceList.getItemCount();
    }
    /**
     * @param args the command line arguments
     */
     /*
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            private DeadlockSim mySim;
            public void run() {
                new ProcessEditorUI(mySim).setVisible(true);
                
            }
        });
    }
      * */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ComputeButton;
    private javax.swing.JLabel ComputeLabel;
    private javax.swing.JTextField ComputeTime;
    private javax.swing.JButton DoneButton;
    private javax.swing.JButton HaltButton;
    private javax.swing.JLabel HaltLabel;
    private javax.swing.JButton OpenButton;
    private javax.swing.JLabel ReleaseLabel;
    private javax.swing.JButton ReleaseResourceButton;
    private javax.swing.JComboBox ReleaseResourceList;
    private javax.swing.JLabel RequestLabel;
    private javax.swing.JButton RequestResourceButton;
    private javax.swing.JButton SaveButton;
    private javax.swing.JComboBox addResourceList;
    private javax.swing.JButton jButtonLoad;
    private javax.swing.JButton jButtonRemove;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea processListing;
    // End of variables declaration//GEN-END:variables

    /*
    public void actionPerformed(ActionEvent e) 
    {
            if(e.getSource() == this.OpenButton) {
               //   new ProcessOpenUI();            
            }
            if (e.getSource() == this.SaveButton) {
                // new ProcessSaveUI();
            }
            if (e.getSource() == this.jButtonLoad) {
                
            }
    }
    */

    class WindowCloser extends WindowAdapter 
    {
          public void windowClosing(WindowEvent e) 
          {
                Window win = e.getWindow();
                win.setVisible(false);
                win.dispose();
          }
    }

}
